const prisma = require('../config/database');
const formatDateTime = require('../utils/formatDateTime');

// 获取对应学科、某几个班的所有考试信息
exports.getExamList = async (req, res) => {
  try {
    const { teacherId, page = 1, pageSize = 10, timeOrder = 'desc' } = req.query;

    if (!teacherId) {
      return res.status(400).json({
        code: 400,
        message: '缺少必要参数: teacherId',
        data: null
      });
    }

    // 验证timeOrder参数
    const validOrder = ['asc', 'desc'].includes(timeOrder) ? timeOrder : 'desc';
    
    const skip = (parseInt(page) - 1) * parseInt(pageSize);
    const take = parseInt(pageSize);

    // 获取教师教授的班级和学科
    const teacherClassesSubjects = await prisma.teacher_classes_subject.findMany({
      where: { teacher_id: parseInt(teacherId) },
      select: {
        classes_id: true,
        subject_id: true
      }
    });

    if (teacherClassesSubjects.length === 0) {
      return res.status(200).json({
        code: 200,
        message: '获取考试列表成功',
        data: {
          list: [],
          total: 0
        }
      });
    }

    const classesIds = [...new Set(teacherClassesSubjects.map(tcs => tcs.classes_id))];
    const subjectIds = [...new Set(teacherClassesSubjects.map(tcs => tcs.subject_id))];

    // 构建班级ID的精确匹配条件
    const classConditions = classesIds.flatMap(classId => [
      { classes_ids: { contains: `,${classId},` } }, // 匹配中间情况
      { classes_ids: { startsWith: `${classId},` } }, // 匹配开头
      { classes_ids: { endsWith: `,${classId}` } },    // 匹配结尾
      { classes_ids: { equals: `${classId}` } }        // 单独存在
    ]);

    // 组合查询条件
    const whereClause = {
      AND: [
        { subject_id: { in: subjectIds } }, // 必须属于教师学科
        { OR: classConditions },            // 并且包含教师班级
        { examination_status: '已批阅' }     // 只获取已批阅的考试
      ]
    };

    // 查询考试列表
    const examinations = await prisma.examination.findMany({
      where: whereClause,
      select: {
        id: true,
        name: true,
        examination_type: true,
        start_time: true,
        end_time: true
      },
      skip,
      take,
      orderBy: { start_time: validOrder } // 使用验证后的timeOrder参数
    });

    // 计算总数
    const totalExaminations = await prisma.examination.count({
      where: whereClause
    });

    const formattedExams = examinations.map(exam => ({
      examinationId: exam.id,
      examinationName: exam.name,
      examinationType: exam.examination_type,
      startTime: formatDateTime(exam.start_time),
      endTime: formatDateTime(exam.end_time)
    }));

    return res.status(200).json({
      code: 200,
      message: '获取考试列表成功',
      data: {
        list: formattedExams,
        total: totalExaminations
      }
    });
    
  } catch (error) {
    console.error('获取考试列表失败:', error);
    return res.status(500).json({
      code: 500,
      message: '获取考试列表失败: ' + error.message,
      data: null
    });
  }
};

// 获取对应考试的自己班级的学生
exports.getStudentOfExam = async (req, res) => {
  try {
    const { examinationId, teacherId, studentAccount, page = 1, pageSize = 10 } = req.query;
    
    // 参数验证
    if (!examinationId || !teacherId) {
      return res.status(400).json({
        code: 400,
        message: '缺少必要参数: examinationId, teacherId',
        data: null
      });
    }

    const skip = (parseInt(page) - 1) * parseInt(pageSize);
    const take = parseInt(pageSize);

    // 1. 获取教师教授的班级
    const teacherClasses = await prisma.teacher_classes_subject.findMany({
      where: { teacher_id: parseInt(teacherId) },
      select: { classes_id: true }
    });

    if (teacherClasses.length === 0) {
      return res.status(200).json({
        code: 200,
        message: '获取学生列表成功',
        data: {
          list: [],
          total: 0
        }
      });
    }

    const classesIds = [...new Set(teacherClasses.map(tc => tc.classes_id))];

    // 2. 获取这些班级的学生ID列表
    const studentClasses = await prisma.student_classes.findMany({
      where: { classes_id: { in: classesIds } },
      select: { student_id: true, classes_id: true }
    });

    const studentIds = [...new Set(studentClasses.map(sc => sc.student_id))];

    // 3. 构建查询条件
    const whereClause = {
      examination_id: parseInt(examinationId),
      user_id: { in: studentIds }
    };

    // 如果提供了学生学号，添加过滤条件
    if (studentAccount) {
      // 使用模糊查询查找符合条件的学生
      const studentsWithMatchingAccount = await prisma.user.findMany({
        where: { 
          account: { contains: studentAccount },
          id: { in: studentIds }
        },
        select: { id: true }
      });
      
      if (studentsWithMatchingAccount.length > 0) {
        // 获取匹配的学生ID列表
        const matchingStudentIds = studentsWithMatchingAccount.map(student => student.id);
        // 更新查询条件，只查找匹配的学生
        whereClause.user_id = { in: matchingStudentIds };
      } else {
        // 如果没有匹配的学生，返回空结果
        return res.status(200).json({
          code: 200,
          message: '获取学生列表成功',
          data: {
            list: [],
            total: 0
          }
        });
      }
    }

    // 4. 查询学生试卷信息
    const studentPapers = await prisma.student_paper.findMany({
      where: whereClause,
      skip,
      take,
      orderBy: { id: 'asc' }
    });

    // 5. 获取结果总数
    const total = await prisma.student_paper.count({ where: whereClause });

    // 6. 获取学生和班级详细信息
    const studentDetails = await Promise.all(
      studentPapers.map(async (paper) => {
        // 获取学生信息
        const student = await prisma.user.findUnique({
          where: { id: paper.user_id }
        });

        if (!student) return null;

        // 获取学生所在班级信息
        const studentClass = await prisma.student_classes.findFirst({
          where: { 
            student_id: student.id,
            classes_id: { in: classesIds }
          }
        });

        if (!studentClass) return null;

        // 获取班级名称
        const classInfo = await prisma.classes.findUnique({
          where: { id: studentClass.classes_id }
        });

        // 查询recheck_request表中是否存在该学生试卷的查卷申请记录
        const recheckRequest = await prisma.recheck_request.findFirst({
          where: { student_paper_id: paper.id },
          select: { status: true }
        });

        // 如果找到记录，返回status，否则返回-1
        const recheckStatus = recheckRequest ? recheckRequest.status : -1;

        return {
          studentId: student.id,
          studentPaperId: paper.id,
          studentAccount: student.account,
          studentName: student.name,
          classesName: classInfo?.name || '未知班级',
          finalScore: paper.total_score || 0,
          recheckStatus: recheckStatus
        };
      })
    );

    // 过滤掉null值
    const filteredStudentDetails = studentDetails.filter(item => item !== null);

    return res.status(200).json({
      code: 200,
      message: '获取学生列表成功',
      data: {
        list: filteredStudentDetails,
        total
      }
    });
    
  } catch (error) {
    console.error('获取学生列表失败:', error);
    return res.status(500).json({
      code: 500,
      message: '获取学生列表失败: ' + error.message,
      data: null
    });
  }
};

// 发起查卷申请
exports.launchRequest = async (req, res) => {
  try {
    const { studentPaperId, requestTeacherId, studentQuestion, teacherComment, originalScore } = req.body;
    
    // 参数验证
    if (!studentPaperId || !requestTeacherId) {
      return res.status(400).json({
        code: 400,
        message: 'error',
        data: '缺少必要参数: studentPaperId, requestTeacherId'
      });
    }

    // 1. 根据教师ID找到对应的学科ID
    const teacherSubject = await prisma.teacher_classes_subject.findFirst({
      where: { teacher_id: parseInt(requestTeacherId) },
      select: { subject_id: true }
    });

    if (!teacherSubject) {
      return res.status(404).json({
        code: 404,
        message: 'error',
        data: '未找到教师所教授的学科'
      });
    }

    // 2. 查找教授同一学科的所有教师
    const teachersWithSameSubject = await prisma.teacher_classes_subject.findMany({
      where: { 
        subject_id: teacherSubject.subject_id
      },
      select: {
        teacher_id: true
      }
    });
    
    // 获取这些教师的ID列表
    const teacherIds = teachersWithSameSubject.map(t => t.teacher_id);
    
    // 从user表中查找这些教师中角色为学科组长的用户
    const subjectLeader = await prisma.user.findFirst({
      where: {
        id: {
          in: teacherIds
        },
        role_id: 2 // 角色为学科组长
      },
      select: {
        id: true
      }
    });

    let subjectLeaderId = null;
    if (subjectLeader) {
      subjectLeaderId = subjectLeader.id;
    } else {
      // 如果在同学科的教师中找不到学科组长，则直接从user表中查询任意学科组长
      const leaderFromUser = await prisma.user.findFirst({
        where: {
          role_id: 2
        },
        select: {
          id: true
        }
      });
      
      if (leaderFromUser) {
        subjectLeaderId = leaderFromUser.id;
      } else {
        return res.status(404).json({
          code: 404,
          message: 'error',
          data: '未找到相关学科组长'
        });
      }
    }

    // 创建东八区当前时间
    const now = new Date();
    const utc8Date = new Date(now.getTime() + (8 * 60 * 60 * 1000));

    // 3. 创建查卷申请记录
    const newRequest = await prisma.recheck_request.create({
      data: {
        student_paper_id: parseInt(studentPaperId),
        request_teacher_id: parseInt(requestTeacherId),
        subject_leader_id: subjectLeaderId,
        student_question: studentQuestion || '',
        teacher_comment: teacherComment || '',
        status: 0, // 待处理
        original_score: parseFloat(originalScore) || 0,
        request_time: utc8Date
      }
    });

    // 4. 检查学科组长是否在线，如果在线，使用socket.io发送消息
    const { io, userList } = require('../index');
    const { getSocketId } = require('../utils/zym-socketIoUtils');
    
    const leaderSocketIds = getSocketId(userList, subjectLeaderId);
    
    if (leaderSocketIds && leaderSocketIds.length > 0) {
      // 学科组长在线，发送socket消息
      leaderSocketIds.forEach(socketId => {
        io.to(socketId).emit('recheckRequest', {
          message: '您有一条查卷申请，请尽快审核',
          requestId: newRequest.id
        });
      });
    }

    // 5. 创建系统通知
    await prisma.system_notification.create({
      data: {
        recipient_id: subjectLeaderId,
        sender_id: null, // 系统发送的通知
        notification_type_id: 4, // 查卷申请通知类型
        content: '您有一条查卷申请，请尽快审核',
        is_read: 0,
        create_time: utc8Date
      }
    });

    return res.status(200).json({
      code: 200,
      message: 'success',
      data: null
    });
    
  } catch (error) {
    console.error('发起查卷申请失败:', error);
    return res.status(500).json({
      code: 500,
      message: 'error',
      data: '发起查卷申请失败: ' + error.message
    });
  }
};

// 查看查卷结果
exports.getRecheckResult = async (req, res) => {
  try {
    const { studentPaperId } = req.query;
    
    // 参数验证
    if (!studentPaperId) {
      return res.status(400).json({
        code: 400,
        message: 'error',
        data: '缺少必要参数: studentPaperId'
      });
    }

    // 在recheck_request表中查找对应studentPaperId的记录
    const recheckRequest = await prisma.recheck_request.findFirst({
      where: { student_paper_id: parseInt(studentPaperId) }
    });

    if (!recheckRequest) {
      return res.status(404).json({
        code: 404,
        message: 'error',
        data: '未找到对应的查卷申请'
      });
    }

    // 在recheck_result表中查找对应recheckRequestId的记录
    const recheckResult = await prisma.recheck_result.findFirst({
      where: { recheck_request_id: recheckRequest.id }
    });

    if (!recheckResult) {
      return res.status(404).json({
        code: 404,
        message: 'error',
        data: '未找到对应的查卷结果'
      });
    }

    // 返回查卷结果
    return res.status(200).json({
      code: 200,
      message: 'success',
      data: {
        originalScore: recheckResult.original_score || 0,
        finalScore: recheckResult.final_score || 0,
        resultSummary: recheckResult.result_summary || '',
        createTime: formatDateTime(recheckResult.create_time)
      }
    });
    
  } catch (error) {
    console.error('获取查卷结果失败:', error);
    return res.status(500).json({
      code: 500,
      message: 'error',
      data: '获取查卷结果失败: ' + error.message
    });
  }
};